package com.chat.config;

import com.chat.dto.MessageDTO;
import com.chat.service.MessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler {

    @Autowired
    private MessageService messageService;

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper;

    public WebSocketHandler() {
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule());
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = getUserIdFromSession(session);
        if (userId != null) {
            sessions.put(userId, session);
            System.out.println("用户连接: " + userId);
        }
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String payload = message.getPayload().toString();
        System.out.println("收到消息: " + payload);
        try {
            MessageDTO messageDTO = objectMapper.readValue(payload, MessageDTO.class);
            // 保存消息
            MessageDTO saved = messageService.saveMessage(messageDTO);
            System.out.println("消息已保存: 从 " + saved.getSenderId() + " 到 " + saved.getReceiverId());
            
            // 只发送给接收者（发送者前端已经立即显示了）
            WebSocketSession receiverSession = sessions.get(messageDTO.getReceiverId());
            if (receiverSession != null && receiverSession.isOpen()) {
                String jsonMessage = objectMapper.writeValueAsString(saved);
                receiverSession.sendMessage(new TextMessage(jsonMessage));
                System.out.println("消息已发送给接收者: " + messageDTO.getReceiverId());
            } else {
                System.out.println("接收者不在线或连接已关闭: " + messageDTO.getReceiverId());
            }
        } catch (Exception e) {
            System.err.println("处理消息时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("WebSocket传输错误: " + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String userId = getUserIdFromSession(session);
        if (userId != null) {
            sessions.remove(userId);
            System.out.println("用户断开连接: " + userId);
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private String getUserIdFromSession(WebSocketSession session) {
        if (session.getUri() == null || session.getUri().getQuery() == null) {
            return null;
        }
        String query = session.getUri().getQuery();
        if (query.contains("userId=")) {
            String[] params = query.split("&");
            for (String param : params) {
                if (param.startsWith("userId=")) {
                    return param.substring("userId=".length());
                }
            }
        }
        return null;
    }

    public void sendMessageToUser(String userId, MessageDTO message) {
        try {
            WebSocketSession session = sessions.get(userId);
            if (session != null && session.isOpen()) {
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

